$(document).ready(function(){
    var username = $('#username'),
        email = $('#email'),
        password = $('#password'),
        password2 = $('#password2');
        
    validate(username,'username',$('#username-help'),"请输入正确的用户名(只含有汉字,数字,字母,下划线不能以下划线开头和结尾,长度为6到15)",/^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]{5,15}$/);
    validate(email,'email',$('#email-help'),"请输入正确的邮箱(example@xxx.com)",/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/);
    simpleValidate(password,$('#password-help'),"请输入正确的密码(以字母开头，长度在6~20之间，只能包含字符,数字和下划线)",/^[a-zA-Z]\w{5,20}$/);
    password2.focus(function(){
        $('#password2-help').text('');
    }).blur(function(){
        var value = $.trim($(this).val());
        var pwd = $.trim($('#password').val());
        if(value != pwd){
            $('#password2-help').text('请输入正确的密码(两次密码不一样)');
        }
    });
    
    $('#submitBtn').click(function(){
       if(username.val() != '' && nick.val() != '' && email.val() != '' && password.val() != '' 
           && profile.val() != '' && password2.val() != ''){
           $(this).submit();
       }else{
           $('#submitBtn-help').text("请正确填写信息");
           return false;
       }
    });
})


function validate(attr, col, help, info, exp){
    attr.focus(function(){
        help.text('');
    }).blur(function(){
        var value = $.trim($(this).val());
        if(exp.test(value)){
            $.ajax({
                type : 'POST',
                dataType : 'json',
                url : '/admin/default/validate',
                data : {
                    'col':col,'colVal':value
                },
                success : function(data){
                    if(data.r == 0 && data.msg){
                        help.text('');
                        help.text(data.msg);
                    }
                }
            });
        }else{
            help.text(info);
        }
    });
}

function simpleValidate(attr,help, info, exp){
    attr.focus(function(){
        help.text('');
    }).blur(function(){
        var value = $.trim($(this).val());
        if(exp.test(value)){
            help.text('');
        }else{
            help.text(info);
        }
    });
}
